<script lang="ts" setup>
import { computed, ref } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import { Button, Divider, message, Space } from 'ant-design-vue'

import { useVbenForm } from '#/adapter/form'
import {colorgetAdd, colorgetUpdata, getColorgetInfo, getColorgetList} from '#/api/colorSeries'
import { getDict } from '#/api/common'
const emit = defineEmits(['refresh'])
const inputDisabled = ref(false)
const colorSystem = ref<any>([])
const warmColor = ref<any>([])
const unevenColor = ref<any>([])
const colorSeriesList = ref([])
const idsArr: any = ref([])



const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    componentProps: {
      class: 'w-4/5',
    },
  },
  layout: 'horizontal',
  schema: [
    {
      component: 'Select',
      fieldName: 'parent_id',
      label: '上级',
      defaultValue:0,
      componentProps: {
        disabled: inputDisabled,
        allowClear: true,
        placeholder: '请输入上级',
        options: colorSeriesList,
      },
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'name',
      label: '名称',
      componentProps: {
        allowClear: true,
        disabled: inputDisabled,
        placeholder: '请输入名称',
      },
      rules: 'required',
    },
    {
      component: 'Select',
      fieldName: 'color_system',
      label: '色系',
      dependencies: {
        show(values) {
          return values.parent_id > 0
        },
        triggerFields: ['parent_id'],
      },
      componentProps: {
        allowClear: true,
        placeholder: '请选择',
        options: colorSystem,
      },
      rules: 'required',
    },
    {
      component: 'Select',
      fieldName: 'warm_color',
      label: '色感',
      dependencies: {
        show(values) {
          return values.parent_id > 0
        },
        triggerFields: ['parent_id'],
      },
      componentProps: {
        allowClear: true,
        placeholder: '请选择',
        options: warmColor,
      },
      rules: 'required',
    },
    {
      component: 'Select',
      fieldName: 'uneven_color',
      label: '深浅色',
      dependencies: {
        show(values) {
          return values.parent_id > 0
        },
        triggerFields: ['parent_id'],
      },
      componentProps: {
        allowClear: true,
        placeholder: '请选择',
        options: unevenColor,
      },
      rules: 'required',
    },
    {
      component: 'Switch',
      fieldName: 'status',
      label: '状态',
      defaultValue: 1,
      componentProps: {
        class: 'w-[50px]',
        checkedValue: 1,
        unCheckedValue: 0,
      },
    },

  ],
  wrapperClass: 'grid-cols-1',
})
const Text: any = computed(() => {
  return idsArr.value.length > 1 ? '保存并编辑下一项' : '保存'
})
const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  class: 'w-[30%] h-[100%]',
  appendToMain: true,
  fullscreenButton: false,
  onCancel() {
    modalApi.close()
    emit('refresh')
  },
  onConfirm: async () => {
    await baseFormApi.validateAndSubmitForm()
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      const { rowData, view } = modalApi.getData<Record<string, any>>()
      // 拿到字典
      const data = await getDict({ keys: ['colorSystem', 'warmColor', 'unevenColor'] })
      colorSystem.value = Object.entries(data.select_list.colorSystem).map(([value, label]) => ({
        value,
        label,
      }))
      warmColor.value = Object.entries(data.select_list.warmColor).map(([value, label]) => ({
        value,
        label,
      }))
      unevenColor.value = Object.entries(data.select_list.unevenColor).map(([value, label]) => ({
        value,
        label,
      }))
      // 拿到上级
      getColorgetList().then((res: any) => {
        colorSeriesList.value = res.list.map((item: any) => ({ value: item.value, label: item.label }))
      })

      if (view === 'add') {
        inputDisabled.value = false
      } else if (view === 'edit') {
        if (Array.isArray(rowData)) {
          // 如果是多个编辑
          idsArr.value = rowData
          initData(rowData[0])
        } else {
          inputDisabled.value = true
          initData(rowData)
        }
      }
    }
  },
})
async function initData(rowData: any) {
  getColorgetInfo({ id: rowData }).then(async (response) => {
    await baseFormApi.setValues(response.row, false)

  })
}

// 保存
async function save() {
  const { valid } = await baseFormApi.validate()
  if (!valid) {
    return
  }
  const values = await baseFormApi.getValues()
  const parmas = {
    ...values,
  }
  if (values.id) {
    // 如果是多个编辑
    if (idsArr.value.length > 1) {
      colorgetUpdata(parmas).then((res: any) => {
        if (res.data.code === 1) {
          message.success(res.data.msg)
          const index = idsArr.value.indexOf(values.id)
          // 如果找到了对应的值，使用 splice 删除它
          if (index !== -1) {
            idsArr.value.splice(index, 1)
            initData(idsArr.value[0])
          }
          emit('refresh')
        } else {
          message.error(res.data.msg)
        }
      })
    } else {
      colorgetUpdata(parmas).then((res: any) => {
        if (res.data.code === 1) {
          message.success(res.data.msg)
          modalApi.close()
          emit('refresh')
        } else {
          message.error(res.data.msg)
        }
      })
    }
  } else {
    colorgetAdd(parmas).then((res: any) => {
      if (res.data.code === 1) {
        message.success(res.data.msg)
        modalApi.close()
        emit('refresh')
      } else {
        message.error(res.data.msg)
      }
    })
  }
}
</script>

<template>
  <Modal :title="inputDisabled ? '编辑' : '新建'">
    <BaseForm>
      <template #_divider>
        <Divider orientation="left">基础信息</Divider>
      </template>
    </BaseForm>
    <template #footer>
      <div class="flex justify-end">
        <Space>
          <Button @click="modalApi.close()">取消</Button>
          <Button type="primary" @click="save()">{{ Text }}</Button>
        </Space>
      </div>
    </template>
  </Modal>
</template>

<style scoped>
.fina-box {
  padding: 10px 0;
}
.fina-btn {
  margin-bottom: 16px;
}
</style>
